package com.tanhua.server;

import com.itheima.commons.utils.Constants;
import com.itheima.commons.utils.JwtUtils;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserFreezeService userFreezeService;

    public void sendMsg(String phone) {

        //根据手机号查询用户，如果用户存在，判断是否被冻结
        User user = userApi.findByMobile(phone);
        if(user != null) {
            userFreezeService.checkUserStatus("1",user.getId(),"您的账号已被冻结！详情请联系管理员");
        }
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //阿里云短信服务
//        smsTemplate.sendSms(phone,code);
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, code.trim(), Duration.ofMinutes(5));
        log.info("Code：" + code);
    }

    /**
     * 检查验证码是否正确
     * @param phone 电话号
     * @param code  验证码
     * @return bool
     */
    public Boolean checkCode(String phone, String code) {
        //获取redis验证码
        String code1 = redisTemplate.opsForValue().get("CHECK_CODE_"+phone);
        //验证码不一致
        if (code1 == null || !code1.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除redis数据库验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        return true;
    }

    /**
     * 登录注册
     */
    public Map loginVerification(String phone, String code) {
        checkCode(phone, code);
//        if (!flag) {
//            throw new RuntimeException("验证码错误");
////            return null;
//        }
        User user = userApi.findByMobile(phone);
        Boolean isNew = false;
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));//org.apache.commons.codec.digest.DigestUtils
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //集成环信，注册环信账号
            Boolean created = huanXinTemplate.createUser("hx" + userId, Constants.INIT_PASSWORD);
            if (created) {
                user.setHxUser("hx" + UserHolder.get());
                user.setPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        Map tokenMap = new HashMap<>();
//        tokenMap.put("id", user.getId());
        tokenMap.put("id", user.getId());
//        tokenMap.put("mobile", user.getMobile());
        tokenMap.put("mobile", user.getMobile());
        String token = JwtUtils.getToken(tokenMap);
        Map retMap = new HashMap<>();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

}
